package com.xinlong.shop.core.util;

import com.xinlong.shop.framework.cache.ICache;
import org.springframework.stereotype.Component;
import wiremock.org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author Sylow
 * @Description 订单通用类
 * @Date: Created in 16:58 2023/6/13
 */
@Component
public class OrderUtil {

    private final ICache cache;

    public OrderUtil(ICache cache) {
        this.cache = cache;
    }

    /**
     * 保证1小时内1万单 不重复
     * @param orderSnType
     * @return
     */
    public String getOrderSn(Integer orderSnType){

        //获取当前时间
        Date currentTime  = new Date();
        //格式化当前时间为【年的后2位+月+日+小时】
        String originDateStr = new SimpleDateFormat("yyMMddHH").format(currentTime );

        //获取【业务编码】 + 【年的后2位+月+日+小时】，作为自增key；
        String prefixOrder = orderSnType + "" + originDateStr;
        //通过key，用缓存 自己实现单秒自增；不同的key，从1开始自增，同时设置60秒过期
        Long incrId = increment(prefixOrder);
        //生成订单编号
        String orderNo = prefixOrder + StringUtils.leftPad(String.valueOf(incrId), 4, '0');

        return orderNo;
    }

    /**
     * 1小时内自增
     * @param key
     * @return
     */
    private Long increment(String key) {
        Object cacheValue = this.cache.get(key);
        if (cacheValue == null) {
            this.cache.put(key, 1L, 60 * 60 );
            return 1L;
        } else {
            Long nextValue = (Long) cacheValue + 1L;
            this.cache.modify(key, nextValue);
            return nextValue;
        }
    }
}
